﻿using MediatR;
using Microsoft.Data.SqlClient;
using S.Authorization.Domain.Model.Organization;
using S.Authorization.Infrastructure;
using S.Authorization.Infrastructure.Interface.Organization;
using S.Authorization.Read.API.Application.Command.OrganizationCommand;
using S.Authorization.Read.API.Dto;

namespace S.Authorization.Read.API.Application.CommandHandlers.OrganizationCommandHandler
{
    /// <summary>
    /// 单位表（企业，集团，系统）
    /// </summary>
    public class BusinessGetCommandHandler : IRequestHandler<BusinessGetCommand, List<GetBusinessDto>>,IRequestHandler<BussinessGetByIdCommand,BusinessModel>
    {
        #region 注入
        private readonly IBusinessModelRepository repository;
        private readonly DbHelper dbHelper;

        public BusinessGetCommandHandler(IBusinessModelRepository repository,DbHelper _dbHelper)
        {
            this.repository = repository;
            this.dbHelper = _dbHelper;
        }

        #endregion

        public async Task<List<GetBusinessDto>> Handle(BusinessGetCommand request, CancellationToken cancellationToken)
        {
            List<BusinessModel> list = await repository.GetAllAsync();
            List<GetBusinessDto> businessList= new List<GetBusinessDto>();
            list.ForEach(x =>
            {
                GetBusinessDto dto = new GetBusinessDto()
                {
                    BusinessId = x.BusinessId,
                    BusinessName = x.BusinessName,
                };
                businessList.Add(dto);

            });
            return businessList;
        }
        /// <summary>
        /// 单位返填
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<BusinessModel> Handle(BussinessGetByIdCommand request, CancellationToken cancellationToken)
        {
            string sql = @"SELECT C.*
                        FROM UsersModel AS A 
                        INNER JOIN (
                            SELECT d1.DepartMentId AS ChildDepartmentId, d2.IndustryTitle
                            FROM DepartmentModel d1
                            JOIN DepartmentModel d2 ON d1.PID = d2.DepartMentId
                        ) B ON A.DepartmentId = B.ChildDepartmentId
                        INNER JOIN BusinessModel AS C ON C.BusinessId = A.BusinessId
                        WHERE A.UserId =@UserId;";
            SqlParameter[] value =
            {
                new SqlParameter("@UserId",request.UserId)
            };
            var list = await dbHelper.GetListDataBySql<BusinessModel>(sql, value);
            return list.FirstOrDefault();
        }
    }
}
